package com.storm.auth.behavior

import com.storm.auth.mapper.ResourceMapper
import com.storm.auth.mapper.UserMapper
import com.storm.auth.mapper.UserRoleMapper
import com.storm.auth.model.data.ResourceVO
import com.storm.auth.model.table.User
import com.storm.auth.model.table.UserRole
import com.storm.common.exception.StormException
import com.storm.util.isnull
import com.storm.datasource.util.queryWrapper

class UserEntity(
    userMapper: UserMapper,
    private val userRoleMapper: UserRoleMapper,
    private val resourceMapper: ResourceMapper,
    id: String? = null,
    private val username: String? = null,
    private val phone: String? = null,
) {
    val userId: String
    val user: User?

    init {
        //根据不同条件获取用户实体
        if (!id.isNullOrBlank()) {
            user = userMapper.selectById(id)
        } else if (!username.isNullOrBlank()) {
            user = userMapper.selectOne(
                queryWrapper {
                    eq(User::username, username)
                }
            )
        } else if (!phone.isNullOrBlank()) {
            user = userMapper.selectOne(
                queryWrapper {
                    eq(User::phone, phone)
                }
            )
        } else {
            throw StormException("获取实体缺乏查询条件")
        }
        userId = user?.userId ?: ""
    }

    /**
     * 实体是否存在
     */
    fun isPresent(): Boolean {
        return !user.isnull()
    }

    /**
     * 若用户信息不存在，抛出异常
     */
    private fun noPresentThrow() {
        if (!isPresent()) {
            throw StormException("用户信息不存在")
        }
    }

    /**
     * 获取用户角色列表
     */
    fun getRoles(): List<String> {
        noPresentThrow()
        return userRoleMapper.selectList(
            queryWrapper {
                eq(UserRole::userId, userId)
            })
            .map { it.roleId }
    }

    /**
     * 获取用户可访问url列表
     */
    fun getResources(): List<ResourceVO> {
        noPresentThrow()
        return resourceMapper.getResourceListByUserId(userId)
            .map { ResourceVO(it.id, it.url, it.method) }
    }


}